<template>
    <div>
        <!--面包屑导航区-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--卡片视图-->
        <el-card>
            <el-row :gutter="30">
                <el-col :span="8">
                    <!--搜索与添加区域-->
                    <el-input placeholder="请输入内容" v-model="queryInfo.key" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!--用户列表区-->
            <el-table :data="users" border stripe>
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column label="用户名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="phone"></el-table-column>
                <el-table-column label="创建时间" prop="created"></el-table-column>
<!--                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
                    </template>
                </el-table-column>-->
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <!--修改-->
                        <el-button type="primary" icon="el-icon-edit" size="mini"
                                   @click="showEditDialog(scope.row.id)"></el-button>
                        <!--删除-->
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
                        <!--分配角色-->
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!--分页区域-->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page=queryInfo.pagenum :page-sizes="[5, 10, 20, 100]" :page-size=queryInfo.pagesize
                           layout="total, sizes, prev, pager, next, jumper" :total="totalPage">
            </el-pagination>
        </el-card>



        <!--添加用户的对话框-->
        <el-dialog
                title="添加用户"
                :visible.sync="addDialogVisible"
                width="50%"
                @close="addDialogClosed"
                :close-on-click-modal=false>
            <!--内容主体区-->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="phone">
                    <el-input v-model="addForm.phone"></el-input>
                </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email"></el-input>
              </el-form-item>
            </el-form>
            <!--底部-->
            <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
        </el-dialog>
        <!--修改用户的对话框-->
        <el-dialog
                title="修改用户"
                :visible.sync="editDialogVisible"
                width="50%"
                :close-on-click-modal=false
        @close="editDialogClose">
          <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
            <el-form-item label="用户名" >
              <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="editForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
          </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserInfo">确 定</el-button>
  </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "Users",
        data() {
            //验证邮箱的验证规则
            var checkEmail = (rule, value, cb) => {
                const regEmail = /^\w+@\w+(\.\w+)+$/
                if (regEmail.test(value)) {
                    return cb
                } else {
                    cb(new Error('请输入合法的邮箱'))
                }

            }

            //验证手机号的验证规则
            var checkMobile = (rule, value, cb) => {
                const regMobile = /^1[34578]\d{9}$/
                if (regMobile.test(value)) {
                    return cb()
                } else {
                    //返回一个错误提示
                    cb(new Error('请输入合法的手机号码'))
                }
            }
            return {
                queryInfo: {
                    key: '',
                    pagenum: 1,
                    pagesize: 10
                },
                totalPage: 0,
                users: [],
                addDialogVisible: false,
                editDialogVisible: false,
                //添加用户的表单数据
                addForm: {
                    username: '',
                    password: '',
                    phone: '',
                    email:''
                },
                editForm:{
                  phone: '',
                  email: ''
                },
                //添加表单验证的规则对象
                addFormRules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min: 3, max: 10, message: '用户名的长度在3~10个字符之间', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 6, max: 15, message: '密码的长度在6~15个字符之间', trigger: 'blur'}
                    ],
                    phone: [
                        {required: true, message: '请输入手机号', trigger: 'blur'},
                        {validator: checkMobile, message: '手机号码不正确，请重新输入', trigger: 'blur'}
                    ],
                },
                editFormRules:{
                  phone: [
                    {required: true, message: '请输入手机号', trigger: 'blur'},
                    {validator: checkMobile, message: '手机号码不正确，请重新输入', trigger: 'blur'}
                  ]
                }
            }
        },
        created() {
            this.getUserList()
        }
        ,
        methods: {
            async getUserList() {
                const res = await this.$http.get('/user/getUserList', {params: this.queryInfo})
                if (res.status !== 200) {
                    return this.$message.error('获取用户列表失败！')
                }

                this.users = res.data.items
                this.totalPage = res.data.total
            }
            ,
            handleSizeChange(newSize) {
                //pagesize改变时触发，当pagesize发生改变的时候，我们应该
                //以最新的pagesize来请求数据并展示数据
                //   console.log(newSize)
                this.queryInfo.pagesize = newSize;
                //重新按照pagesize发送请求，请求最新的数据
                this.getUserList();
            }
            ,
            handleCurrentChange(current) {
                //页码发生改变时触发当current发生改变的时候，我们应该
                //以最新的current页码来请求数据并展示数据
                //   console.log(current)
                this.queryInfo.pagenum = current;
                //重新按照pagenum发送请求，请求最新的数据
                this.getUserList();
            }
            ,
            //监听switch状态的改变
            async userStateChange(userInfo) {
                const {data: res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
                if (res.meta.status !== 200) {
                    userInfo.mg_state = !userInfo.mg_state
                    return this.$message.error('更新用户状态失败！')
                }
                this.$message.success(res.meta.msg)
            },
            //监听对话框的关闭事件
            addDialogClosed() {
                this.$refs.addFormRef.resetFields()

            },

            // 点击按钮，添加新用户
            async addUser() {
                await this.$refs.addFormRef.validate(async valid => {
                  if (!valid) {
                    return
                  }
                  // 可以发起添加用户的网络请求
                  const res = await this.$http.post('user/register', this.addForm);
                  console.log(res)
                  if (res.status !== 201) {
                    this.$message.error('添加用户失败！')
                  }

                  this.$message.success('添加用户成功！')
                  // 隐藏添加用户的对话框
                  this.addDialogVisible = false
                  // 重新获取用户列表数据
                  await this.getUserList()
                })
            },

            async showEditDialog(id) {
                const res = await this.$http.get('user/select/' + id)
              if (res.status!==200){
                this.$message.error('获取用户信息失败！')
              }
              this.editForm = res.data
                this.editDialogVisible = true
            },
          editDialogClose(){
            this.$refs.editFormRef.resetFields()
          },

          //修改用户信息
          async editUserInfo(){
            await this.$refs.editFormRef.validate(async valid => {
              if (!valid) {
                return
              }
              const res = await this.$http.put('user/update', this.editForm)
              if (res.status !== 200) {
                this.$message.error('修改用户信息失败')
              }

              // 隐藏添加用户的对话框
              this.editDialogVisible = false
              // 重新获取用户列表数据
              await this.getUserList()
              this.$message.success("修改用户信息成功")
            })
          },
          //删除用户
           async removeUserById(id) {
             this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
               confirmButtonText: '确定',
               cancelButtonText: '取消',
               type: 'warning'
             }).then(async () => {
               const res = await this.$http.delete("user/delete/" + id)
               if (res.status !== 200) {
                 this.$message.error('删除用户失败')
               }
               this.$message({
                 type: 'success',
                 message: '删除成功!'
               });
               await this.getUserList()
             }).catch(() => {
               this.$message({
                 type: 'info',
                 message: '已取消删除'
               });
             });
           }
        }
    }
</script>
